package com.longfor.dragonshard.service.impl;

import com.longfor.dragonshard.entity.Demo;
import com.longfor.dragonshard.mapper.DemoMapper;
import com.longfor.dragonshard.service.IDemoService;
import com.longfor.dragonshard.service.base.AbstractBaseService;
import com.longfor.drogon.common.LFConstants;
import com.longfor.drogon.common.exception.LFBizException;
import com.longfor.drogon.common.util.LFDefaultKeyGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * Demo Service类
 *
 * @author chi.zhang
 * @version v1.0
 * @create 2017-10-05 下午2:28
 **/
@Service
@CacheConfig(cacheNames = LFConstants.CACHE.DEFAULT_CACHE_NAME)
public class DemoServiceImpl extends AbstractBaseService<Demo> implements IDemoService {
    private Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);

    @Autowired
    private DemoMapper demoMapper;

    @Override
    @Cacheable(key = "#p0")
    public Optional<Demo> selectById(Long id) {
        return Optional.ofNullable(demoMapper.selectByPrimaryKey(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(Demo demo) {
        LFDefaultKeyGenerator defaultKeyGenerator = new LFDefaultKeyGenerator();
        demo.setId(defaultKeyGenerator.generateKey());
        demoMapper.insertSelective(demo);

        return demo.getId();
    }

    @Override
    @CachePut(key = "#p0.id")
    public void update(Demo demo) {
        demoMapper.updateByPrimaryKeySelective(demo);
    }

    @Override
    @CacheEvict(key = "#p0")
    public Integer delete(Long id) {
        return demoMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据业务需求，重写该方法
     *
     * @param list
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertList(List<Demo> list) {
        //todo 业务实现
        LFDefaultKeyGenerator defaultKeyGenerator = new LFDefaultKeyGenerator();
        for(Demo demo : list){
            demo.setId(defaultKeyGenerator.generateKey());
        }

        return demoMapper.insertList(list);
    }

}
